package com.jsb.laundry.common.utils.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.codec.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;

public class AES {

    public static boolean initialized = false;


    public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws Exception {

        initialize();

        try {

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

            Key sKeySpec = new SecretKeySpec(keyByte, "AES");

            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化

            byte[] result = cipher.doFinal(content);

            return result;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    public static void initialize() {

        if (initialized) {

            return;

        }

        Security.addProvider(new BouncyCastleProvider());

        initialized = true;

    }

    //生成iv

    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {

        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");

        params.init(new IvParameterSpec(iv));

        return params;

    }


    public static void main(String[] args) throws Exception {
//AESUtils微信获取手机号解密工具类

        AES aes = new AES();
        String encryptedData = "tbCYHCCBKFk34QC3Nb+rKufBhm6Ov+4wqI/1R4K+ggwPpuvKuvYpDBRmsyiys4K2wjPvYaBpauSjotWOARPjQaB8rHPeQqeLB4NG7npgMFqIjuK7pV+ySsQ+CfSZkc6hqbIqzj0x8svd7FYEk4RZNuztS0qDNg38BC/arQfCIE9gYRZx2C90uhU+e4sxfC0vbPJ3b4kfXCoBkLXLS1Yufw==";
                String iv = "VszSDsrGZIl01vX0GZJVHw==";
        String sessionKey ="R/PFWfwvMktNDcQWkz2uKQ==";
        //调用AESUtils工具类decrypt方法解密获取json串

        byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData.getBytes(StandardCharsets.UTF_8)), Base64.decodeBase64(sessionKey.getBytes(StandardCharsets.UTF_8)), Base64.decodeBase64(iv.getBytes(StandardCharsets.UTF_8)));

        //判断返回参数是否为空

        if (null != resultByte && resultByte.length > 0) {

            String jsons = new String(resultByte, "UTF-8");

            System.out.println(jsons);

            JSONObject json = JSON.parseObject(jsons);

            //json解析phoneNumber值

            String phoneNumber = json.getString("phoneNumber");

            System.out.println("phoneNumber：" + phoneNumber);
        }
    }
}